import os
from django.conf import settings

from .models import RoadType, ScenicArea, BackgroundMusic


def get_scenic_area_children(scenic, scenictype):
    from .serializers import SimpleScenicAreaSerializer
    children = ScenicArea.objects.filter(scenic_area=scenic, is_delete=False)
    if not children:
        return None
    scenictype = int(scenictype)
    return SimpleScenicAreaSerializer([item for item in children if (
        (scenictype == 0 and item.scenic_area_type is None)
        or (item.scenic_area_type is not None 
            and item.scenic_area_type.id == scenictype))], many=True).data


def get_tiles_img(area_map):
    return area_map.map_image.path

def get_tiles_uri(area_map):
    return os.path.join(settings.MEDIA_URL, 'maps', 'tiles_%d' % area_map.scenic_area.id, area_map.map_identifier.hex)
    
def get_tiles_full_dir(area_map):
    return os.path.join(settings.MEDIA_ROOT, 'maps', 'tiles_%d' % area_map.scenic_area.id)

def get_tiles_full_path(area_map):
    return os.path.join(get_tiles_full_dir(area_map), area_map.map_identifier.hex)


def save_scenic_audio(tmp_file, voice_filename, inst):
    from filer.models.filemodels import File as ModelFile
    from filer.models.filemodels import Folder as ModelFolder

    foder_name= 'speech'
    forder = ModelFolder.objects.filter(name=foder_name)
    if not forder:
        forder = ModelFolder.objects.create(name=foder_name)
    else:
        forder = forder[0]
    bg = inst.bg_audio_file
    modify_db = 0
    if not bg:
        bgs = BackgroundMusic.objects.filter(default=True)
        if bgs:
            bg = bgs[0].bg_audio_file
            modify_db = bgs[0].modify_db
    else:
        modify_db = inst.modify_db
    modify_db = 0 if modify_db is None else modify_db
    if bg:
        from pydub import AudioSegment
        input_music_1 = AudioSegment.from_mp3(tmp_file) #需要修改的地方：音频1
        input_music_2 = AudioSegment.from_mp3(bg.path)#需要修改的地方：音频2
        input_music_2 += modify_db
        # 混合音频
        sound2_repeats_until_sound1_ends = input_music_1.overlay(input_music_2, loop=True)
        #复杂输入合并之后的音频
        # bitrate：比特率，album：专辑名称，artist：歌手，cover：封面图片
        #需要修改的地方：输出音频。cover那个没用着，可以删掉。
        sound2_repeats_until_sound1_ends.export(tmp_file, format="mp3", bitrate="8k")

    with open(tmp_file, 'rb') as f:
        from django.core.files import File
        myfile = File(f)
        inst.audio_file = ModelFile(name=voice_filename, file=myfile, folder=forder)
        inst.audio_file.save()
        inst.save()

def encrypt_scenic_id(id):
        import base64
        from common import aes
        encrypt_data = aes.AESCipher(settings.SCENIC_KEY).encrypt('%d' % id)
        return base64.b64encode(encrypt_data.encode()).decode()

def dencrypt_scenic_id(data):
        import base64
        from common import aes
        base64_data = base64.b64decode(data.encode()).decode()
        return aes.AESCipher(settings.SCENIC_KEY).decrypt(base64_data)

def isInteger(s):
    try:
        int(s)
        return True
    except:
        return False

def get_scenicid_s(scenicid):
    try:
        scenicid = int(scenicid)
    except:
        scenicid = int(dencrypt_scenic_id(scenicid))
    return scenicid

def get_qrcode_filepath(scenicid):
    qrcode_dir = os.path.join(settings.MEDIA_ROOT, 'qrcode')
    os.makedirs(qrcode_dir, exist_ok=True)
    filename = encrypt_scenic_id(scenicid) + '.png'
    return settings.MEDIA_URL + 'qrcode/' + filename, os.path.join(qrcode_dir, filename)
